package com.canglion.ragflow.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.canglion.ragflow.RAGFlowClient;
import com.canglion.ragflow.constant.SdkConstant;
import com.canglion.ragflow.exception.RAGFlowException;
import com.canglion.ragflow.pojo.kb.KbApiResponse;

/**
 * rundreams.blog.csdn.net
 *
 * @Time:2025/9/4
 * @Author: Zihao Zhang
 * @description:
 */

public class KnowledgeBaseService {

    private final RAGFlowClient client;

    public KnowledgeBaseService(RAGFlowClient client) {
        this.client = client;
    }

    /**
     * 创建知识库
     */
    public KbApiResponse create(String name) {
        String url = client.getBaseUrl() + "/v1/kb/create";

        JSONObject body = JSONUtil.createObj()
                .set("name", name);

        HttpResponse response = HttpRequest.post(url)
                .header(SdkConstant.Authorization, client.getAuthManager().getAccessToken())
                .header("Content-Type", "application/json")
                .body(body.toString())
                .timeout(10000)
                .execute();

        if (!response.isOk()) {
            throw new RAGFlowException("Create KB failed: " + response.getStatus());
        }

        // 使用 Hutool 将 JSON 转为 ApiResponse 对象
        return JSONUtil.toBean(response.body(), KbApiResponse.class, true);
    }

    /**
     * 获取知识库列表
     */
    public JSONObject list() {
        String url = client.getBaseUrl() + "/api/v1/kb/list";

        HttpResponse response = HttpRequest.get(url)
                .header("authorization", client.getAuthManager().getAccessToken())
                .timeout(10000)
                .execute();

        if (!response.isOk()) {
            throw new RAGFlowException("Failed to list KBs: " + response.getStatus());
        }

        return JSONUtil.parseObj(response.body());
    }

    /**
     * 删除知识库
     */
    public boolean delete(String kbId) {
        String url = client.getBaseUrl() + "/api/v1/kb/" + kbId + "/delete";

        HttpResponse response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + client.getAuthManager().getAccessToken())
                .timeout(10000)
                .execute();

        return response.isOk();
    }
}
